﻿using System;
//using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Configuration;
using SaveConnectionStringDemo;
//using System.Collections;

// http://stackoverflow.com/questions/3457589/setting-up-visual-studio-2010-to-set-as-auto-increment-version-of-project-on-each

// Simple proxy Sample
// http://wpfsamples.codeplex.com/releases/view/16580

namespace TCPServer
{
    class Program
    {  
        static void Main(string[] args)
        {
            try
            {
                //ParseCommandLine(args);

                // Generate a random name to show AddAndSaveOneConnectionStringSettings works.
                // You never do this in production code.
                //var connectionStringName = "TestConnectionConnectionString." + DateTime.Now.ToString("yyyy.MM.dd.HH.mm.ss");

                //// Create a connection string element.
                //ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(connectionStringName,
                //    "LocalSqlServer: data source=127.0.0.1;Integrated Security=SSPI;" + "Initial Catalog=aspnetdb",
                //    "System.Data.SqlClient");

                //Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                ////DumpToConsole(ConfigurationManager.ConnectionStrings, "Before AddAndSaveOneConnectionStringSettings.");

                //SaveConnectionString.AddAndSaveOneConnectionStringSettings(configuration,
                //    connectionStringSettings);

                Console.WriteLine("...");
                SIGGREProto.Server server = new SIGGREProto.Server();
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + "-Error: " + ex.Message + ": \nStackTrace" + ex.StackTrace);
                //throw;
            }

            //But what use is a server without a client to connect to it? 
            // This tutorial is mainly about the server, but here's a quick 
            // piece of code that shows you how to set up a basic TCP connection and send it a piece of data.

        }

        // TODO : Parse command line
        // http://www.codeproject.com/KB/cs/CommandLineArgumentParser.aspx?display=Print

        static void ParseCommandLine(string[] args)
        {
            //nationalized output is not wanted. make it all english.
            System.Globalization.CultureInfo MyCulture = new System.Globalization.CultureInfo("en-US");
            System.Threading.Thread.CurrentThread.CurrentCulture = MyCulture;
            System.Threading.Thread.CurrentThread.CurrentUICulture = MyCulture;

            //initialize CommandLineArgumentParser and set up parameters.
            CLAParser.CLAParser CmdLine = new CLAParser.CLAParser("CLAParserTest");
            CmdLine.ParameterPrefix = "/";

            bool UseMathExample = false;
            if (UseMathExample)
            {
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "output", CLAParser.CLAParser.ValueType.OptionalString, "Write output to file, if no file specified default file output.txt is used.");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "add", CLAParser.CLAParser.ValueType.MultipleInts, "Do a mathematical addition of number given integers.");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "v", CLAParser.CLAParser.ValueType.MultipleBool, "Activate verbose output, multiple " + CmdLine.ParameterPrefix + "v increase verbosity even more.");
            }
            else
            {
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "ConnectionString", CLAParser.CLAParser.ValueType.String, "no help");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "Scriptfile", CLAParser.CLAParser.ValueType.String, "no help");
                CmdLine.Parameter(CLAParser.CLAParser.ParamAllowType.Optional, "", CLAParser.CLAParser.ValueType.String, "filename");
                //CmdLine.AllowAdditionalParameters = true;
            }

            //do command line parsing, if exception caught display it and show usage information to user.
            try
            {
                CmdLine.Parse();
            }
            catch (CLAParser.CLAParser.CmdLineArgumentException Ex)
            {
                Console.WriteLine(Ex.Message);
                Console.WriteLine("");
                Console.WriteLine(CmdLine.GetUsage());
                Console.WriteLine("");
                Console.WriteLine(CmdLine.GetParameterInfo());
                if (System.Diagnostics.Debugger.IsAttached)
                    Console.ReadKey();
                return;
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now + "-Error: " + ex.Message + ": \nStackTrace" + ex.StackTrace);
                //throw;
            }

            //do what has to be done by program.
            if (CmdLine.Count != 0) //if there is a required parameter found, this if is not necessary.
            {
                int verbose = 0;
                string output_string = "";
                string output_file = null;

                if (CmdLine["v"] != null)
                {
                    verbose = Convert.ToInt32(CmdLine["v"]);
                    output_string += "Verbose output at level: " + CmdLine["v"] + "\r\n";
                }
                if (CmdLine["output"] != null)
                {
                    if (verbose > 0) output_string += CmdLine.ParameterPrefix + "output paramater found.\r\n";
                    if (CmdLine["output"] == "")
                    {
                        output_file = "output.txt";
                        if (verbose > 2) output_string += "Default output file is used.\r\n";
                    }
                    else { output_file = CmdLine["output"]; }
                    if (verbose > 1) output_string += "Output file is: " + output_file + "\r\n";
                }
                if (CmdLine["add"] != null)
                {
                    if (verbose > 0) output_string += CmdLine.ParameterPrefix + "add paramater found.\r\n";
                    int result = 0;
                    System.Text.RegularExpressions.Regex Split = new System.Text.RegularExpressions.Regex("[\\s]+");
                    string[] numbers = Split.Split(CmdLine["add"]);
                    foreach (string n in numbers)
                    {
                        if (verbose > 1) output_string += "Adding " + n + " to result.\r\n";
                        result += Convert.ToInt32(n);
                        if (verbose > 2) output_string += "Intermediate result now: " + result.ToString() + "\r\n";
                    }
                    output_string += "Result of addition is: " + result.ToString() + "\r\n";
                }

                if (verbose > 3)
                {
                    output_string += "Listing of all arguments and their values:\r\n";
                    foreach (DictionaryEntry arg in CmdLine)
                    {
                        output_string += "Argument: \"" + arg.Key + "\" -> Value: \"" + arg.Value + "\"\r\n";
                    }

                }

                Console.Write(output_string);
                if (output_file != null)
                {
                    try
                    {
                        System.IO.File.WriteAllText(output_file, output_string);
                        if (verbose > 0)
                            Console.Write("Output file written.");
                    }
                    catch (Exception Ex)
                    {
                        Console.Write("Exception while writing output file: " + Ex.Message);
                    }

                }
            }
            else
            {
                Console.WriteLine(CmdLine.GetUsage());
                Console.WriteLine("");
                Console.WriteLine(CmdLine.GetParameterInfo());
            }

            if (UseMathExample == false)
            {
                IEnumerator e = CmdLine.GetEnumerator();
                while (e.MoveNext())
                {
                    DictionaryEntry arg = (DictionaryEntry)e.Current;
                    Console.WriteLine(arg.Key + "=" + arg.Value);
                }
            }

            if (System.Diagnostics.Debugger.IsAttached)
                Console.ReadKey();
        }
    }
}
